# -*- python -*-
# ex: set syntax=python:

from buildbot.plugins import *

# This is a sample buildmaster config file. It must be installed as
# 'master.cfg' in your buildmaster's base directory.

# This is the dictionary that the buildmaster pays attention to. We also use
# a shorter alias to save typing.
c = BuildmasterConfig = {}

####### BUILDSLAVES

# The 'slaves' list defines the set of recognized buildslaves. Each element is
# a BuildSlave object, specifying a unique slave name and password.  The same
# slave name and password must be configured on the slave.
c['slaves'] = [buildslave.BuildSlave("example-slave", "pass")]

# 'protocols' contains information about protocols which master will use for
# communicating with slaves. You must define at least 'port' option that slaves 
# could connect to your master with this protocol.
# 'port' must match the value configured into the buildslaves (with their
# --master option)
c['protocols'] = {'pb': {'port': 9989}}

####### CHANGESOURCES

# the 'change_source' setting tells the buildmaster how it should find out
# about source code changes.  Here we point to the buildbot clone of pyflakes.

#Gerrit Configuration
gerrit_url = "gerrit.example.com"
gerrit_user = "gerrit"
gerrit_port = "29418"
gerrit_project = "mygerritproject"

gerrit_repo = "ssh://%s@%s:%s/%s" % (gerrit_user, gerrit_url, gerrit_port,
                                     gerrit_project)

#Add comment-added to handled_events to have approvals information (Code-Review...)
c['change_source'] = []
c['change_source'].append(changes.GerritChangeSource(gerrit_url, gerrit_user,
                                                handled_events=["patchset-created",
                                                                "comment-added"]))

####### SCHEDULERS

# Configure the Schedulers, which decide how to react to incoming changes.  In this
# case, just kick off a 'runtests' build

#Check there is Code-Review=+2 in Approvals (of comment-added)

def change_code_review_plus_2(change):
    if "event.approvals" in change.properties:
        for a in change.properties["event.approvals"]:
            if "Code-Review" in a["type"] and int(a["value"]) == 2:
               return True
    return False


c['schedulers'] = []
c['schedulers'].append(schedulers.SingleBranchScheduler(
                            name="all",
                            change_filter=util.ChangeFilter(branch_re="master/*", filter_fn=change_code_review_plus_2),
                            treeStableTimer=None,
                            builderNames=["runtests-gcc","runtests-clang"]))
c['schedulers'].append(schedulers.ForceScheduler(
                            name="force",
                            builderNames=["runtests-gcc","runtests-clang"]))

####### BUILDERS

# The 'builders' list defines the Builders, which tell Buildbot how to perform a build:
# what steps, and which slaves can execute them.  Note that any particular build will
# only take place on one slave.

#Build with GCC
f_gcc = util.BuildFactory([
    steps.Gerrit(repourl=gerrit_repo, mode="full",retry=[60,60],timeout=3600),
    steps.ShellCommand(command=["bash","./autogen.sh"],timeout=3600),
    steps.Configure(command=["./configure"]),
    steps.Compile(command=["make", "-j", "4"]),
    steps.Compile(command=["make", "test"])
])

#Build with Clang
f_clang = BuildFactory([
    steps.Gerrit(repourl=gerrit_repo, mode="full",retry=[60,60],timeout=3600),
    steps.ShellCommand(command=["bash","./autogen.sh"],timeout=3600),
    steps.Configure(command=["./configure"],env={ "CC":"clang", "CXX":"clang++"}),
    steps.Compile(command=["make", "-j", "4"]),
    steps.Compile(command=["make", "test"])
])

c['builders'] = []
c['builders'].append(
    util.BuilderConfig(name="runtests-gcc", slavenames=["example-slave"],
                       factory=f_gcc))
c['builders'].append(
    util.BuilderConfig(name="runtests-clang", slavenames=["example-slave"],
                       factory=f_clang))


####### STATUS TARGETS

# 'status' is a list of Status Targets. The results of each build will be
# pushed to these targets. buildbot/status/*.py has a variety to choose from,
# like IRC bots.

c['status'] = []

authz_cfg=authz.Authz(
    # change any of these to True to enable; see the manual for more
    # options
    auth=auth.BasicAuth([("pyflakes","pyflakes")]),
    gracefulShutdown = False,
    forceBuild = 'auth', # use this to test your slave once it is set up
    forceAllBuilds = False,
    pingBuilder = False,
    stopBuild = False,
    stopAllBuilds = False,
    cancelPendingBuild = False,
)
c['status'].append(html.WebStatus(http_port=8010, authz=authz_cfg))

def gerritReviewCB(builderName, build, result, master, arg):
    if result == util.RETRY:
        return dict()

    message =  "Buildbot finished compiling your patchset\n"
    message += "on configuration: %s\n" % builderName
    message += "The result is: %s\n" % util.Results[result].upper()

    if arg:
        message += "\nFor more details visit:\n"
        message += build['url'] + "\n"

    if result == util.SUCCESS:
        verified = 1
    else:
        verified = -1

    return dict(message=message, labels={'Verified': verified})

def gerritStartCB(builderName, build, arg):
    message = "Buildbot started compiling your patchset\n"
    message += "on configuration: %s\n" % builderName
    message += "See your build here: %s" % build['url']

    return dict(message=message)

def gerritSummaryCB(buildInfoList, results, status, arg):
    success = False
    failure = False

    msgs = []

    for buildInfo in buildInfoList:
        msg = "Builder %(name)s %(resultText)s (%(text)s)" % buildInfo
        link = buildInfo.get('url', None)
        if link:
            msg += " - " + link
        else:
            msg += "."

        msgs.append(msg)

        if buildInfo['result'] == util.SUCCESS:
            success = True
        else:
            failure = True

    if success and not failure:
        verified = 1
    else:
        verified = -1

    return dict(message='\n\n'.join(msgs),
                labels={
                    'Verified': verified
                })

c['buildbotURL'] = 'http://buildbot.example.com/'
c['status'].append(status.GerritStatusPush(gerrit_url, gerrit_user,
                                           reviewCB=gerritReviewCB,
                                           reviewArg=c['buildbotURL'],
                                           startCB=gerritStartCB,
                                           startArg=c['buildbotURL'],
                                           summaryCB=gerritSummaryCB,
                                           summaryArg=c['buildbotURL']))

####### PROJECT IDENTITY

# the 'title' string will appear at the top of this buildbot installation's
# home pages (linked to the 'titleURL').

c['title'] = "Buildbot with Gerrit"
c['titleURL'] = "https://" + gerrit_url

# the 'buildbotURL' string should point to the location where the buildbot's
# internal web server is visible. This typically uses the port number set in 
# the 'www' entry below, but with an externally-visible host name which the 
# buildbot cannot figure out without some help.

c['buildbotURL'] = "http://localhost:8010/"

# minimalistic config to activate new web UI
c['www'] = dict(port=8010,
                plugins=dict(waterfall_view={}, console_view={}))

####### DB URL

c['db'] = {
    # This specifies what database buildbot uses to store its state.  You can leave
    # this at its default for all but the largest installations.
    'db_url' : "sqlite:///state.sqlite",
}
